var revenueApi = require('../../script/revenue.js');
var publicApi = require('../../script/public.js');
var config = require('../../script/config.js');
import Uploader from 'miniprogram-file-uploader';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: config.baseUrl,
    DETAIL_ID: '',
    OrderInfo: null,
    AuditType: [],
    SubmitData: {
      AUDIT_REMARK: '',
      ADD_FILES: [],
      DELETE_FILES: [],
      AUDIT_CONFIG: [],
      DETAIL_ID: '',
      ISSPOTPHOTO: '',
      IS_DISPOSE: 0,
      isAddBlack: 0,
      BLACK_TYPE: ''
    },
    imgList: [], // 显示的图片列表
    imgFileList: [], // 上传的图片文件列表
    videoFileList: [], // 上传的视频文件列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options) {
      this.setData({
        DETAIL_ID: options.id,
      });
      this.getDetail();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.GetPCodes();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  GetPCodes() {
    publicApi.GetPCodes({
      keys: ['AuditType'],
    }).then(res => {
      this.setData({
        AuditType: res.data.AuditType,
      })
    })
  },
  getDetail() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    const params = {
      Data: JSON.stringify({
        DETAIL_ID: this.data.DETAIL_ID,
      }),
    }
    revenueApi.ViewCheckDetail(params).then(res => {
      if (res.code === 200) {
        this.setData({
          OrderInfo: res.data
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 1500
        });
      }
    }).finally(() => {
      wx.hideLoading();
    })
  },
  onCkChange(e) {
    this.setData({
      'SubmitData.AUDIT_CONFIG': e.detail,
    });
  },
  disposeChange(e) {
    const value = parseInt(e.currentTarget.dataset.value);
    this.setData({
      'SubmitData.IS_DISPOSE': value
    });
  },
  blackChange(e) {
    const value = parseInt(e.currentTarget.dataset.value);
    this.setData({
      'SubmitData.isAddBlack': value
    });
  },
  remarkChange(e) {
    this.setData({
      'SubmitData.AUDIT_REMARK': e.detail.value
    });
  },

  /************ 附件上传 ************/
  chooseImage: function () {
    if (this.data.imgFileList.length >= 5) {
      wx.showToast({
        title: '最多只能上传5张图片！',
        icon: "none",
        duration: 2000
      })
      return
    }
    const _this = this;
    // 上传图片
    wx.chooseImage({
      count: 4 - this.data.imgFileList.length, //默认9
      sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        wx.showLoading({
          mask: true,
          title: '上传中...'
        });
        const tempFiles = res.tempFiles;
        _this.uploadOneByOne(tempFiles, 0, 0, 0, tempFiles.length);
      }
    });
  },
  async uploadOneByOne(imgPaths, successUp, failUp, count, length) {
    var that = this;
    const token = wx.getStorageSync(config.storageKey.token)
    const xtoken = wx.getStorageSync(config.storageKey.xtoken)
    // const addWatermarkRes = await that.addWatermark(imgPaths[count].path) //先加水印
    if (imgPaths[count].path) {
      wx.uploadFile({
        url: config.baseUrl + '/api/Upload/Upload',
        method: "POST",
        header: {
          'Authorization': 'Bearer ' + token,
          'X-Authorization': 'Bearer ' + xtoken
        },
        filePath: imgPaths[count].path,
        // filePath: addWatermarkRes,
        name: 'file',
        timeout: 120000, // 超时时间
        success: (resf) => {
          if (resf.statusCode === 200) {
            const resData = JSON.parse(resf.data);
            if (resData && resData.code === 200) {
              successUp++; //成功+1
              const relData = resData.data;
              const file = {
                FileName: relData[0],
                FilePath: relData[0],
                Size: imgPaths[count].size
              }
              that.setData({
                imgList: that.data.imgList.concat(config.baseUrl + '/' + relData[0]),
                imgFileList: that.data.imgFileList.concat(file)
              })
            } else {
              failUp++; //失败+1
            }
          } else {
            failUp++; //失败+1
          }
        },
        fail: function (e) {
          failUp++; //失败+1
        },
        complete: function (e) {
          count++; //下一张
          if (count == length) {
            if (successUp > 0) {
              wx.showToast({
                title: '已上传' + successUp + "张图片",
                icon: 'success',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: "图片上传失败",
                icon: 'error'
              })
            }
          } else {
            that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
          }
        }
      })
    } else {
      failUp++; //失败+1
      count++; //下一张
      if (count != length) {
        that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
      }
    }
  },
  previewImage: function (e) {
    //预览图片
    const that = this;
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: that.data.imgList[index],
      urls: that.data.imgList
    })
  },
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    wx.showModal({
      title: "提示",
      content: "是否要删除该图片",
      success: (res) => {
        if (res.confirm) {
          const imgList = [...this.data.imgList]
          const imgFileList = [...this.data.imgFileList]
          imgList.splice(index, 1);
          imgFileList.splice(index, 1);
          this.setData({
            imgList: imgList,
            imgFileList: imgFileList
          })
        }
      }
    })
  },
  chooseVideo: function () {
    const that = this;
    // if (that.data.videoFileList.length >= 3) {
    //   wx.showToast({
    //     title: '最多只能上传3个视频！',
    //     icon: "none",
    //     duration: 2000
    //   })
    //   return
    // }
    const token = wx.getStorageSync(config.storageKey.token);
    const xtoken = wx.getStorageSync(config.storageKey.xtoken);
    // 上传视频
    wx.chooseMedia({
      count: 1,
      maxDuration: 300,
      compressed: true,
      camera: 'back',
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      success: (responent) => {
        wx.getVideoInfo({
          src: responent.tempFiles[0].tempFilePath,
          success(res) {
            const isLarge = res.size > 60 * 1024;
            if (isLarge) {
              wx.showToast({
                title: '单个视频不能大于60MB！',
                icon: "none"
              });
              return;
            } else {
              wx.showLoading({
                mask: true,
                title: '视频上传中...'
              });
              // 分片上传
              if (Uploader.isSupport()) {
                const uploader = new Uploader({
                  tempFilePath: responent.tempFiles[0].tempFilePath,
                  totalSize: responent.tempFiles[0].size,
                  uploadUrl: config.baseUrl + '/api/Upload/UploadPartFile',
                  mergeUrl: config.baseUrl + '/api/Upload/MergeFile',
                  verifyUrl: config.baseUrl + '/api/Upload/CheckFile',
                  testChunks: true,
                  timeout: 100000,
                  fileName: responent.tempFiles[0].tempFilePath.slice(responent.tempFiles[0].tempFilePath.length - 10),
                  header: {
                    Authorization: 'Bearer ' + token
                    // X-Authorization: 'Bearer ' + xtoken
                  },
                })
                uploader.upload();

                // 文件上传成功
                uploader.on('success', (res) => {
                  const videoFileList = {
                    FileName: res.url,
                    FilePath: res.url,
                    Size: responent.tempFiles[0].size
                  };
                  that.setData({
                    videoFileList: that.data.videoFileList.concat(videoFileList)
                  })
                  wx.showToast({
                    title: "视频上传成功",
                    icon: 'success',
                    duration: 2000
                  })
                })

                // 文件上传失败
                uploader.on('fail', (res) => {
                  wx.showToast({
                    title: '视频上传失败！',
                    duration: 2000
                  });
                })
              }
            }
          },
          fail(err) {
            console.log(err)
          }
        })
      }
    })
  },
  deletetVideo(e) {
    const that = this;
    var index = e.currentTarget.dataset.index;
    wx.showModal({
      title: "提示",
      content: "是否要删除此视频",
      success: (res) => {
        if (res.confirm) {
          const videoFileList = [...that.data.videoFileList]
          videoFileList.splice(index, 1);
          that.setData({
            videoFileList: videoFileList
          })
        }
      }
    })
  },
  // 提交
  DoSubmit() {
    if (this.data.SubmitData.AUDIT_CONFIG.length == 0) {
      wx.showToast({
        title: '请至少选择一个检查项',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    if (this.data.SubmitData.AUDIT_REMARK == '') {
      wx.showToast({
        title: '请填写稽查情况说明',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    const files = this.data.imgFileList.concat(this.data.videoFileList);
    const params = {
      Data: JSON.stringify({
        DETAIL_ID: this.data.DETAIL_ID,
        AUDIT_CONFIG: this.data.SubmitData.AUDIT_CONFIG.join(','),
        AUDIT_REMARK: this.data.SubmitData.AUDIT_REMARK,
        ADD_FILES: files
      }),
    }
    revenueApi.UpdateTaskState(params).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    }).catch(() => {
       wx.hideLoading();
    })
  }
})